document.addEventListener('DOMContentLoaded', function() {
  // DOM Elements
  const companyNameInput = document.getElementById('companyName');
  const sealNameInput = document.getElementById('sealName');
  const sealCodeInput = document.getElementById('sealCode');
  const sealSizeInput = document.getElementById('sealSize');
  const lineWidthSelect = document.getElementById('lineWidth');
  const centerScaleInput = document.getElementById('centerScale');
  const mainSizeInput = document.getElementById('mainSize');
  const mainRingSpaceInput = document.getElementById('mainRingSpace');
  const sealNameSizeInput = document.getElementById('sealNameSize');
  const sealNameUpSpaceInput = document.getElementById('sealNameUpSpace');
  const generateBtn = document.getElementById('generateBtn');
  const downloadBtn = document.getElementById('downloadBtn');
  
  // Canvas elements
  const canvas = document.getElementById('sealCanvas');
  const ctx = canvas.getContext('2d');
  
  // Configuration state
  let sealConfig = {
    sealSize: 168,
    lineWidth: 4,
    centerScale: 25,
    mainSize: 18,
    mainRingSpace: 1,
    sealNameSize: 18,
    sealNameUpSpace: 50
  };
  
  // State variables
  let sealImageBase64 = '';
  
  // Event Listeners for all inputs
  const allInputs = document.querySelectorAll('input, select');
  allInputs.forEach(input => {
    input.addEventListener('change', updateConfig);
  });
  
  generateBtn.addEventListener('click', generateSeal);
  downloadBtn.addEventListener('click', downloadSeal);
  
  // Initialize UI
  function init() {
    // Load saved config if exists
    chrome.storage.local.get(['sealConfig'], function(result) {
      if (result.sealConfig) {
        sealConfig = { ...sealConfig, ...result.sealConfig };
        updateConfigInputs();
      }
    });
  }
  
  // Update configuration from inputs
  function updateConfig() {
    // Read all values from inputs
    sealConfig.sealSize = parseInt(sealSizeInput.value) || 168;
    sealConfig.lineWidth = parseInt(lineWidthSelect.value) || 4;
    sealConfig.centerScale = parseInt(centerScaleInput.value) || 25;
    sealConfig.mainSize = parseInt(mainSizeInput.value) || 21;
    sealConfig.mainRingSpace = parseInt(mainRingSpaceInput.value) || 5;
    sealConfig.sealNameSize = parseInt(sealNameSizeInput.value) || 18;
    sealConfig.sealNameUpSpace = parseInt(sealNameUpSpaceInput.value) || 50;
    
    // Save config
    chrome.storage.local.set({ sealConfig: sealConfig });
    
    // Update canvas size
    canvas.width = sealConfig.sealSize;
    canvas.height = sealConfig.sealSize;
  }
  
  // Update configuration inputs from state
  function updateConfigInputs() {
    // Set all input values from config
    sealSizeInput.value = sealConfig.sealSize;
    lineWidthSelect.value = sealConfig.lineWidth;
    centerScaleInput.value = sealConfig.centerScale;
    mainSizeInput.value = sealConfig.mainSize;
    mainRingSpaceInput.value = sealConfig.mainRingSpace;
    sealNameSizeInput.value = sealConfig.sealNameSize;
    sealNameUpSpaceInput.value = sealConfig.sealNameUpSpace;
    
    // Update canvas size
    canvas.width = sealConfig.sealSize;
    canvas.height = sealConfig.sealSize;
  }
  
  // Generate seal based on inputs
  function generateSeal() {
    // Clear canvas
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    
    const companyName = companyNameInput.value;
    const sealName = sealNameInput.value;
    
    // Validate inputs
    if (!companyName) {
      alert('请输入公司名称');
      return;
    }
    
    // Update config before generating
    updateConfig();
    
    // Generate the company seal
    generateRoundSeal(companyName, sealName);
    
    // Enable download button
    downloadBtn.disabled = false;
  }
  
  // Generate standard round company seal
  function generateRoundSeal(companyName, sealName) {
    const size = sealConfig.sealSize;
    const centerX = size / 2;
    const centerY = size / 2;
    const radius = size / 2 - 5;  // Adjusted to give a slight margin
    
    // Draw outer circle
    ctx.beginPath();
    ctx.arc(centerX, centerY, radius, 0, Math.PI * 2);
    ctx.strokeStyle = 'red';
    ctx.lineWidth = sealConfig.lineWidth;
    ctx.stroke();
    
    // Draw center emblem (star)
    const starRadius = (radius * sealConfig.centerScale) / 100;
    drawStar(centerX, centerY, starRadius);
    
    // Draw company name around the circle
    drawCircleText(companyName, centerX, centerY, radius);
    
    // Draw seal name at the bottom
    drawSealName(sealName, centerX, centerY);
    
    // Save the generated image
    sealImageBase64 = canvas.toDataURL('image/png');
  }
  
  // Draw text in a circle (following sealmanager.html implementation)
  function drawCircleText(text, centerX, centerY, radius) {
    // Save the current state
    ctx.save();
    
    // Move to the center of the circle
    ctx.translate(centerX, centerY);
    
    // Set text properties
    ctx.font = `${sealConfig.mainSize}px 宋体`;
    ctx.fillStyle = 'red';
    ctx.textAlign = 'center';
    ctx.textBaseline = 'middle';
    
    // Get count of characters
    const count = text.length;
    
    // Skip if no text
    if (count <= 0) {
      ctx.restore();
      return;
    }
    
    // Calculate the angle between each character
    const angle = 4 * Math.PI / (3 * (count - 1));
    
    // Draw each character
    const chars = text.split('');
    for (let i = 0; i < count; i++) {
      // The character to draw
      const char = chars[i];
      
      // Rotate to position
      if (i === 0) {
        ctx.rotate(5 * Math.PI / 6);
      } else {
        ctx.rotate(angle);
      }
      
      // Save state before moving outward
      ctx.save();
      
      // Calculate radius to position text
      const adjustedRadius = radius - sealConfig.lineWidth - sealConfig.mainSize * 1.4 / 2 - sealConfig.mainRingSpace;
      ctx.translate(adjustedRadius, 0);
      
      // Rotate 90 degrees to make character parallel to x-axis
      ctx.rotate(Math.PI / 2);
      
      // Scale to make character appear more natural
      ctx.scale(1, 1.4);
      
      // Draw the character (no weight setting)
      ctx.fillText(char, 0, 0); // Center point
      
      // Restore state to continue positioning characters
      ctx.restore();
    }
    
    // Restore original context state
    ctx.restore();
  }
  
  // Draw seal name at the bottom
  function drawSealName(text, centerX, centerY) {
    ctx.save();
    
    // Set font and color
    ctx.font = `${sealConfig.sealNameSize}px SimHei`;
    ctx.fillStyle = 'red';
    ctx.textAlign = 'center';
    ctx.textBaseline = 'middle';
    
    // Draw at the position specified by sealNameUpSpace
    const y = centerY + parseInt(sealConfig.sealNameUpSpace);
    
    // Draw text (no weight setting)
    ctx.fillText(text, centerX, y, 1.2 * (sealConfig.sealSize / 2)); // Limit width to prevent overflow
    
    ctx.restore();
  }
  
  // Draw a 5-pointed star (exactly as in sealmanager.html)
  function drawStar(centerX, centerY, radius) {
    ctx.save();
    ctx.fillStyle = 'red';
    ctx.translate(centerX, centerY);
    ctx.rotate(Math.PI); // Rotate to position
    ctx.beginPath();
    
    const dig = Math.PI / 5 * 4;
    for (let i = 0; i < 5; i++) {
      const x = Math.sin(i * dig) * radius;
      const y = Math.cos(i * dig) * radius;
      
      if (i === 0) {
        ctx.moveTo(x, y);
      } else {
        ctx.lineTo(x, y);
      }
    }
    
    ctx.closePath();
    ctx.stroke();
    ctx.fill();
    ctx.restore();
  }
  
  // Download generated seal
  function downloadSeal() {
    if (!sealImageBase64) {
      alert('请先生成印章');
      return;
    }
    
    const downloadLink = document.createElement('a');
    const sealCode = sealCodeInput.value || '印章';
    
    downloadLink.href = sealImageBase64;
    downloadLink.download = `${sealCode}.png`;
    downloadLink.click();
  }
  
  // Initialize
  init();
  
  // Auto-generate on load
  setTimeout(() => {
    if (companyNameInput.value && sealNameInput.value) {
      generateSeal();
    }
  }, 500);
}); 